package com.wpfly.SpringBootDemo.controller.home;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
@RequestMapping("/home/index")
public class IndexController {

    private Logger log = LoggerFactory.getLogger(IndexController.class);

    @GetMapping("/upload")
    public String upload(Model model)
    {
        model.addAttribute("siteName", "Spring测试");
        return "/home/index/upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("upload") MultipartFile file)
    {
        if(file.isEmpty())
        {
            return "请选择文件";
        }
        String fileName = file.getOriginalFilename();
        String uploadPath = System.getProperty("user.dir").replace("\\","/") + "/upload/";
        //检查文件夹
        File temp = new File(uploadPath);
        if(!temp.exists())
        {
            temp.mkdirs();
        }
        if(!temp.isDirectory())
        {
            return "文件夹创建失败";
        }
        //目标文件
        File dest = new File(uploadPath + fileName);
        //日志
        log.info(dest.getAbsolutePath());
        log.info(dest.canWrite()?"可以写入":"不可以写入");
        //保存
        try {
            file.transferTo(dest);
            return "上传成功";
        }catch (Exception e)
        {
            log.error(e.toString(), e);
        }
        return "上传失败";
    }

    @GetMapping("/info")
    @ResponseBody
    public String info(){
        String uploadPath = new File("").getAbsolutePath().replace("\\","/") + "/upload/";
        String uploadPath2 = System.getProperty("user.dir").replace("\\","/") + "/upload/";
        return uploadPath + "====" + uploadPath2;
    }
}
